﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using RBS.Common;
using RBS.Common.JsonEntity;
using Webdiyer.WebControls.Mvc;

namespace RBS.Web.Controllers
{
    public class YdController : BaseController
    {
        //
        // GET: /YD/ 

        public ActionResult SetOrder(int hotelid, int orderid = 0)
        {
            if (User.Identity.Name == "")
            {
                return RedirectToAction("Index", "Login", new { redirectUrl = Request.Url });
            }
            var user = CurrentUser;
            var model = new RBS.Core.Model.D_Order
            {
                H_Id = hotelid,
                ContactUser = user.U_Name,
                ContactMobile = user.Mobile
            };
            ViewBag.DineTable = "";
            if (orderid != 0)
            {
                model = new RBS.Core.BLL.D_Order().GetModelList(" Id=" + orderid + "and U_Id=" + CurrentUser.Id).FirstOrDefault();
                if (model != null && model.OrderState > 3)
                {
                    return RedirectToAction("Error", "Home");
                }
                if (model != null) ViewBag.DineTable = model.DineTable;
            }
            return View(model);
        } 
        [HttpPost]
        public ActionResult SetOrder(FormCollection collection)
        {
            //修改订单
            var ordermodel = AddOrder(collection);
            var uid = Convert.ToInt32(User.Identity.Name);
            //修改桌位信息  
            // UpdateSeatStatus(collection["DineTable"], collection["OldDineTable"], int.Parse(collection["H_Id"]));
            //修改菜单
            //UpdateDetail(oid, uid);  
            return RedirectToAction("SetCookBook", new { id = ordermodel.H_Id, orderid = ordermodel.Id });  
        }

        public RBS.Core.Model.D_Order AddOrder(FormCollection collection)
        {
            var oid = -1;
            var a = collection;
            var model = new RBS.Core.Model.D_Order
            {
                OrderChannel = "网站预定",
                ContactUser = collection["ContactUser"],
                ContactMobile = collection["ContactMobile"],
                OrderRemark = collection["OrderRemark"],
                ReserveDate = collection["ReserveDate"],
                ReserveTime = collection["ReserveTime"],
                DineNum = int.Parse(collection["DineNum"]),
                H_Id = int.Parse(collection["H_Id"]),
                DineTable = int.Parse(collection["DineTable"]),
                Dinecondition = collection["Dinecondition"],
                PayTime = DateTime.Now,
                CreateTime = DateTime.Now,
                U_Id = Convert.ToInt32(User.Identity.Name),
                LastModifyDate = DateTime.Now
            };
            model.OrderTime = Convert.ToDateTime(model.ReserveDate + " " + model.ReserveTime);
            model.HotelName = new RBS.Core.BLL.Hotel.H_Hotels().GetModelByCache(model.H_Id).H_Name;
            var bll = new RBS.Core.BLL.D_Order();
            try
            {
                if (collection["Id"] != "0")
                {
                    model.Id = Convert.ToInt32(collection["Id"]);
                    model.OrderState = 2;
                    bll.Update(model); 
                }
                else
                {
                    model.OrderState = 1;
                    oid = bll.Add(model);
                    model.Id = oid;
                }
            }
            catch
            {
                oid = -1;
            } 
            return model;
        } 
        public ActionResult SetCookBook(int id, int orderid = 0, string type="add")
        {
            var model = new RBS.Core.BLL.Hotel.H_Hotels().GetModel(id);
            ViewBag.orderid = orderid;
            ViewBag.Type = type;
            ViewBag.IsGuest = 0;
            if (orderid != 0)
            {
                var bll = new RBS.Core.BLL.D_Order_Details();
                var bllguest = new RBS.Core.BLL.D_Guest(); 
                var isGuest = bll.ExistsOrderId(orderid, CurrentUser.Id) ;
                ViewBag.IsGuest = !isGuest? 1 : 0;
                if (isGuest || bllguest.ExistsOrderId(orderid, CurrentUser.Id))
                {
                    var items =  new RBS.Core.BLL.V_OrderDetails().GetModelList(" orderid=" + orderid );
                    Session[RBSKeys.SESSION_SHOPCAR_INFO] = items;
                    ViewBag.orderid = orderid;
                }
            }
            return View(model);
        } 
        public ActionResult SetFriend(int id = 1, int orderid = 0, string kword = null)
        {
            const int pageSize = 10;

            var bll = new RBS.Core.BLL.U_Friends();
            // var admin = GetAdminInfo(); //取得当前管理员信息
            if (kword != null) kword = kword.Replace("'", "");
            var strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(kword))
            {
                //strTemp.Append(" and (H_UID like  '%" + kword + "%' or H_UserName like '%" + kword + "%')");
            }
            string strWhere = " and UserId=" + CurrentUser.Id + strTemp.ToString();
            const string orderby = " id  desc";
            var startIndex = id;

            int totalItems = 0; //要分页的总记录数
            DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems).Tables[0];
            //PagedList构造函数 
            var list = IListDataSet.DataTableToIList<RBS.Core.Model.U_Friends>(dt);
            PagedList<RBS.Core.Model.U_Friends> arts = null;
            if (list != null)
                arts = new PagedList<RBS.Core.Model.U_Friends>(list, id, pageSize, totalItems);
            else
            {
                list = new List<RBS.Core.Model.U_Friends>();
                arts = new PagedList<RBS.Core.Model.U_Friends>(list, id, pageSize, totalItems);
            }

            ViewBag.OrderId = orderid;
            return View(arts);
        } 
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult InviteFriend(string ids, string orderid, string returnUrl)
        {
            var ret = new JsonReturnMessages();
            try
            {
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                {
                    var model = new RBS.Core.Model.D_Guest
                    {
                        GuestId = Convert.ToInt32(id),
                        OrderId = Convert.ToInt32(orderid),
                        Status = 0
                    };
                    new RBS.Core.BLL.D_Guest().Add(model);
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败！";
                return Json(ret);
            }
            ret.IsSuccess = true;
            ret.Msg = "操作成功";
            ret.Data = !string.IsNullOrEmpty(returnUrl) ? returnUrl : Url.Action("Invite");
            return Json(ret);
        }

        public JsonResult GetSeatStatus(int sid,string time)
        {
            var ret = new JsonReturnMessages();
            var time1 = Convert.ToDateTime(time).AddHours(-3);
            var time2 = Convert.ToDateTime(time).AddHours(3); 
            ret.IsSuccess = new RBS.Core.BLL.D_Order().Seat(sid, time1, time2); 
            return Json(ret,JsonRequestBehavior.AllowGet); 
        } 
    }
}
